import {
  forEach,
  isArray,
  isDate,
  isObject,
  isURLSearchParams,
  KeyVal,
} from "./utils";

export const encode = (val: string) => {
  return encodeURIComponent(val)
    .replace(/%3A/gi, ":")
    .replace(/%24/g, "$")
    .replace(/%2C/gi, ",")
    .replace(/%20/g, "+")
    .replace(/%5B/gi, "[")
    .replace(/%5D/gi, "]");
};

// 绑定url参数
export const bindUrl = (
  url: string,
  params: KeyVal | undefined,
  paramsSerializer: Function | undefined
): string => {
  if (!params) {
    return url;
  }
  var serializedParams;
  if (paramsSerializer) {
    serializedParams = paramsSerializer(params);
  } else if (isURLSearchParams(params)) {
    serializedParams = params.toString();
  } else {
    const parts = [] as string[];

    forEach(params, function serialize(val: unknown, key: string) {
      if (val === null || typeof val === "undefined") {
        return;
      }

      if (isArray(val)) {
        key = key + "[]";
      } else {
        val = [val];
      }

      forEach(val as KeyVal, function parseValue(v: unknown) {
        if (isDate(v)) {
          v = (v as Date).toISOString();
        } else if (isObject(v)) {
          v = JSON.stringify(v);
        }
        parts.push(encode(key) + "=" + encode(v as string));
      });
    });

    serializedParams = parts.join("&");
  }

  if (serializedParams) {
    var hashmarkIndex = url.indexOf("#");
    if (hashmarkIndex !== -1) {
      url = url.slice(0, hashmarkIndex);
    }

    url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
  }
  return url;
};
